package com.binyouwei.udp_lib.factory;

import android.util.Log;

import androidx.annotation.NonNull;

import com.binyouwei.udp_lib.ReceiveMessageInterface;
import com.binyouwei.udp_lib.SingleThreads;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author 宾有为
 * @date 2024/6/11 20:05
 * @link https://blog.csdn.net/baidu_41616022?type=blog
 * @describe：任播（代码由copilot生成，未经实际测试）
 **/
public class AnycastFactory implements UdpFactory{
    final int port = 6666;
    final String TAG = getClass().getSimpleName();
    boolean isFinish = false;

    @Override
    public void initUdp() {
        isFinish = true;
    }

    @Override
    public void destroyUdp() {
        isFinish = false;
    }

    @Override
    public void sendMessage(@NonNull String ip, @NonNull String message) {
        SingleThreads.getInstance().execute(() -> {
            try {
                byte[] bytes = message.getBytes();
                // 任播 ip 一般为 239.255.255.255
                InetAddress inet = InetAddress.getByName(ip);
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inet, port);
                DatagramSocket datagramSocket = new DatagramSocket();
                datagramSocket.send(packet);
                Log.e(TAG, "发送任播成功，message：" + message);
            } catch (IOException e) {
                Log.e(TAG, "发送任播失败，message：" + e.getMessage());
                e.printStackTrace();
            }
        });
    }

    @Override
    public void onReceiveMessageListener(@NonNull String ip,@NonNull ReceiveMessageInterface receiveMessage) {
        SingleThreads.getInstance().execute(() -> {
            try {
                // 创建缓冲区以接收数据
                byte[] receiveData = new byte[1024];
                DatagramSocket socket = new DatagramSocket(port);
                socket.setBroadcast(true);
                while (isFinish) {
                    // 创建DatagramPacket来接收数据
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    // 接收广播消息
                    socket.receive(receivePacket);
                    // 处理接收到的数据
                    String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    receiveMessage.onReceiveMessageListener(message);
                    Log.e(TAG, "任播收到一条消息，message：" + message);
                }
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "任播接收消息失败，message：" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }
}
